import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:yp/Xwidgets/button_widget.dart';
import 'package:yp/Xwidgets/cache_image.dart';
import 'package:yp/Xwidgets/line.dart';
import 'package:yp/Xwidgets/navigation_bar.dart';
import 'package:yp/config/style.dart';
import 'package:yp/utils/util.dart';
import 'package:yp/pages/logistics/state.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../helper.dart';
import 'logic.dart';

/// 物流追踪
class LogisticsTracking extends StatefulWidget {
  @override
  _LogisticsTrackingState createState() => _LogisticsTrackingState();
}

class _LogisticsTrackingState extends State<LogisticsTracking> with SingleTickerProviderStateMixin {
  final LogisticsLogic logic = Get.put(LogisticsLogic());
  final LogisticsLogicState state = Get.find<LogisticsLogic>().state;

  @override
  void initState() {
    super.initState();
    state.tabController = TabController(initialIndex: 0, length: state.tabList.length, vsync: this);
    state.tabController.addListener(() {
      //点击tab时或滑动tab回调一次
      if (state.tabController.index == state.tabController.animation.value) {
        logic.changeTab(state.tabController.index);
      }
      // //点击tab回调一次，滑动切换tab不会回调
      // if(state.tabController.indexIsChanging){
      //   logic.changeTab(state.tabController.index);
      // }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: YPXNavigationBar('物流追踪'),
        backgroundColor: EsColors.White,
        body: GetBuilder<LogisticsLogic>(builder: (logic) {
          return Column(
            children: [
              if (state.tabList.length > 1) _tabHeadder(),
              _logisticsList(),
            ],
          );
        }));
  }

  ///  tab栏切换的头部
  Widget _tabHeadder() {
    return Visibility(
      visible: (state?.tabList?.length ?? 0) > 0,
      child: Container(
        color: EsColors.White,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: ExtendedTabBar(
          tabs: List<Widget>.generate(state?.tabController?.length ?? 0, (int index) => state?.tabList[index]),
          controller: state.tabController,
          labelPadding: EdgeInsets.zero,
          labelColor: EsColors.Primary,
          isScrollable: (state?.tabController?.length ?? 0) > 5,
          unselectedLabelColor: EsColors.TitleSecondary,
          indicatorSize: TabBarIndicatorSize.label,
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          indicator: const ExtendedUnderlineTabIndicator(
              // size: 30,
              borderSide: BorderSide(color: EsColors.Primary, width: 2)),
        ),
      ),
    );
  }

  /// 下边对应的列表
  Widget _logisticsList() {
    return Expanded(
      child: TabBarView(
          controller: state.tabController,
          physics: NeverScrollableScrollPhysics(),
          children: List<Widget>.generate(
              state?.tabController?.length ?? 0,
              (int index) => SingleChildScrollView(
                    child: Column(
                      children: [
                        state.products != null && state.products.length > 0 ? _logisticsInfo() : Container(),
                        state.products != null && state.products.length > 0 ? _goodsInfo() : Container(),
                        YpLine(height: 20, thickness: 20, color: EsColors.BackGroundSecondary,),

                        // 物流地图
                        _logisticsMapView(),

                        ListView.builder(
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                            itemBuilder: (context, index) {
                              return _progress(
                                state?.logisticsInfoList[index]['selected'],
                                state?.logisticsInfoList[index]['oper_info'],
                                state?.logisticsInfoList[index]['create_dtme'],
                                state?.logisticsInfoList[index]['oper_desc'],
                                top: index == 0,
                                end: index == (state?.logisticsInfoList?.length ?? 0) - 1,
                                // msg: state.logisticsInfoList[index]['tips'] ??''
                              );
                            },
                            itemCount: state?.logisticsInfoList?.length ?? 0),
                      ],
                    ),
                  )).toList()),
    );
  }

  // 物流地图
  Widget _logisticsMapView() {
    return Visibility(
      visible: state.logisticsMapUrl.length > 0,
      child: SizedBox(
        width: MediaQuery.of(context).size.width,
        height: (MediaQuery.of(context).size.height - MediaQuery.of(context).padding.top - MediaQuery.of(context).padding.bottom - 344 - 55),
        child: Column(
          children: [
            Expanded(
              child: WebView(
                initialUrl: state.logisticsMapUrl,  //需要打开的url
                //是否支持js 默认是不支持的，
                javascriptMode: JavascriptMode.unrestricted,
                gestureRecognizers: [Factory(() => EagerGestureRecognizer())].toSet(),
                onWebViewCreated: (WebViewController webViewController) {
                  state.currentWebViewController = webViewController;
                },
                navigationDelegate: (NavigationRequest request) {
                  if (request.url.startsWith('tel:')) {
                    launch(request.url);
                    return NavigationDecision.prevent;
                  }
                  return NavigationDecision.navigate;
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 物流信息
  Widget _logisticsInfo() {
    return Container(
      decoration: EsDecoration.BoxShadowWithRadius,
      margin: EdgeInsets.fromLTRB(16, 12, 16, 10),
      padding: EdgeInsets.all(12),
      child: Column(
        children: [
          Row(
            children: [
              Image(image: AssetImage('assets/images/level.png'), width: 32, height: 32, fit: BoxFit.fill),
              SizedBox(width: 8),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  print('打快递电话');
                  logic.launchTelURL(state.phone);
                },
                child: Visibility(
                  visible: state.tranSimName != null ? true : false,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text(state?.tranSimName ?? '', style: TextStyle(color: EsColors.TitleSecondary, fontSize: EsSizes.MD, fontWeight: EsFontWeights.Medium)),
                      Row(
                        children: [
                          Text('官方电话：${state.phone ?? ''}', style: TextStyle(color: EsColors.TitleSecondary, fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal)),
                          // Icon(
                          //   Icons.arrow_forward_ios,
                          //   size: EsSizes.XS,
                          //   color: EsColors.TitleSecondary,
                          // ),
                        ],
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
          SizedBox(height: 15),
          Row(
            children: [
              Text('快递编号：', style: TextStyle(color: EsColors.TitleSecondary, fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal)),
              Text(state?.wayBillCode ?? '', style: TextStyle(color: EsColors.TitleSecondary, fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal)),
              SizedBox(width: 4),
              EsOutLineButton(
                '复制',
                onTap: () {
                  print('复制快递单号');
                  Clipboard.setData(ClipboardData(text: state?.wayBillCode?.toString() ?? '')).then((value) => toast('复制成功'));
                },
                fontSize: EsSizes.XXS,
                normal: true,
                padding: EdgeInsets.symmetric(vertical: 1, horizontal: 4),
              ),
            ],
          )
        ],
      ),
    );
  }

  /// 商品信息
  Widget _goodsInfo() {
    return Container(
      color: EsColors.White,
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('共计${state?.totalQty ?? 0}件商品', style: TextStyle(color: EsColors.ContentSecondary, fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal)),
          Container(
              height: 60,
              margin: EdgeInsets.only(top: 10, bottom: 6),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  ListView.builder(
                      scrollDirection: Axis.horizontal,
                      shrinkWrap: true,
                      itemBuilder: (context, index) => CachedImage(
                            margin: EdgeInsets.only(right: 10),
                            width: 60,
                            height: 60,
                            path: state.products[index]['item_picture'] ?? '',
                            border: Border.all(color: EsColors.BackGround, width: 1),
                          ),
                      itemCount: state.products.length ?? 0),
                ],
              )),
        ],
      ),
    );
  }

  /// 物流进度
  Widget _progress(bool selected, String text, String time, String title, {bool top = false, bool end = false, String msg = ''}) {
    return IntrinsicHeight(
      child: Container(
        color: EsColors.White,
        padding: EdgeInsets.symmetric(horizontal: 12),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              padding: const EdgeInsets.only(top: 20, right: 5),
              width: 0,
              child: Column(
                children: [
                  // Visibility(
                  //   visible: time == null ? false : true,
                  //   child: Text(
                  //     time == null ? '' : getDayFromTimestamp(time),
                  //     style: TextStyle(color: EsColors.Content, fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal),
                  //   ),
                  // ),
                  // Visibility(
                  //   visible: time == null ? false : true,
                  //   child: Text(
                  //     time == null ? '' : getMinFromTimestamp(time),
                  //     style: TextStyle(color: EsColors.Content, fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal),
                  //   ),
                  // ),
                ],
              ),
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  color: top ? Colors.transparent : EsColors.BackGround,
                  width: 1,
                  height: 20,
                ),
                Icon(
                  Icons.radio_button_checked,
                  color: selected ? Colors.deepOrange : EsColors.BackGround,
                ),
                Expanded(
                  child: Container(
                    color: end ? Colors.transparent : EsColors.BackGround,
                    width: 1,
                  ),
                )
              ],
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(top: 18, left: 8),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Visibility(
                      visible: title?.isNotEmpty ?? false,
                      child: Expanded(

                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            title ?? '',
                            style: TextStyle(color: selected ? Colors.deepOrange : Colors.grey, fontSize: EsSizes.MD, fontWeight: EsFontWeights.Bold),
                          ),
                            Text(
                             time ?? '',
                            style: TextStyle(color: selected ? Colors.deepOrange : Colors.grey, fontSize: EsSizes.SM, fontWeight: EsFontWeights.Bold),
                          )
                        ],
                      )),
                    ),
                    Visibility(
                      visible: text?.isNotEmpty ?? false,
                      child: Expanded(
                          child: Text(
                        text ?? '',
                        style: TextStyle(color: selected ? Colors.deepOrange : EsColors.TitleSecondary, fontSize: EsSizes.MD, fontWeight: EsFontWeights.Normal),
                      )),
                    ),
                    Visibility(
                      visible: msg?.isNotEmpty ?? false,
                      child: Padding(
                        padding: const EdgeInsets.only(top: 4),
                        child: Text(
                          msg,
                          style: TextStyle(color: EsColors.Content, fontSize: EsSizes.SM, fontWeight: EsFontWeights.Normal),
                        ),
                      ),
                    ),
                    SizedBox(height: 10)
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
